<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>属性分组页面</title>

    <style>
        .box1{
            float:left;
            width: 20%;
            height: auto;
        }
        .box2{
            float:left;
            width: 80%;
            height: auto;
        }


    </style>
</head>
<script src="../../static/global.js"></script>
<script src="../../static/axios.min.js"></script>
<script src="../../static/vue.min.js"></script>
<body>
<!-- 查询所有属性、分类、分组 -->
<form id="attrgroupForm"  lay-filter="attrgroupFormfilter" style="display: none" class="layui-form"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->

    <div class="layui-form-item">
        <label class="layui-form-label">商品分组</label>
        <div class="layui-input-block">
            <select name="attr_group_id" lay-verify="required">
                <option value="">--请选择商品分组--</option>
                <option v-for="group in resultGroup"  v-bind:value="group.attr_group_id"  v-model="resultGroup">{{group.attr_group_name}}</option>
            </select>
        </div>
    </div>
    <!-- -->
    <div class="layui-form-item">
        <label class="layui-form-label">属性分类</label>
        <div class="layui-input-block">
            <select name="attr_id" lay-verify="required">
                <option value="">--请选择属性--</option>
                <option v-for="attr in resultAttr" v-bind:value="attr.attr_id" >{{attr.attr_name}}</option>
            </select>
        </div>
    </div>
    <input type="hidden" name="catelog_id" id="catalogIdByForm">
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addcententtable">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!-- 修改分组名 -->
<form style="display: none" id="groupNameForm" class="layui-form" action="">
    <div class="layui-form-item">
        <label class="layui-form-label">分组名</label>
        <div class="layui-input-block">
            <input type="text" name="groupName" id="groupName" required  lay-verify="required" placeholder="请输入分组名" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo" id="groupNameBtn">立即提交</button>
        </div>
    </div>
</form>
<!-- 修改分类下的分组 -->
<div id="transferByGroup" style="display: none"></div>

<!-- table 和tree  -->
<div>
    <div id="catalogTree" class="box1"></div>
    <div class="box2">
        <input type="button" id="notattrgroup" class="layui-btn  layui-btn-warm " value="查看非分类分组">
        <input type="button" id="addgroupby" class="layui-btn  layui-btn-normal " value="添加非分类分组">
        <table id="catalogTab" lay-filter="toolfilter"></table>
    </div>
</div>

<div style="display: none;margin-left: 50px;margin-top: 20px" id="div_add_group">
    <form id="add_add_group" lay-filter="add_add_group" class="layui-form layui-form-pane">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">分组名</label>
                <div class="layui-input-block">
                    <input type="text" name="attr_group_name" lay-verify="required" placeholder="请输入分组名"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">排序</label>
                <div class="layui-input-block">
                    <input type="number" name="sort" lay-verify="required" placeholder="请输入分组名" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-filter="btn_add_addgroup" id="btn_add_addgroup">添加</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>


</body>


<script>
    //查询全部的属性和分组和商品分类来渲染到页面上的select标签上
    let attrVue=new Vue({
        el:'#attrgroupForm',
        data:{
            resultAttr:[],
            resultGroup:[],
            resultCatelog:[]
        },
        methods:{
            attrGroupCatalog(attrvue_catid){
               // alert(attrvue_catid);
                axios.get(glodate.serverZuul+"category/getAttrGroupCatalogvo",{params:{'cat_id':attrvue_catid}})
                    .then(res=>{
                        //    console.log(res.data.pms_attr_groups);
                        this.resultGroup=res.data.pms_attr_groups;
                        console.log(this.resultGroup);
                        this.resultAttr=res.data.pms_attrs;
                        this.resultCatelog=res.data.pms_categoryList;

                    })
            }
        },
        updated:function(){
            layui.use(['form', 'layer'], function () {
                form = layui.form;
                form.render()
            });
        }

    })

    layui.use(['layer','form','tree','table','transfer'],function (){
        let tree=layui.tree;
        let form=layui.form;
        let layer=layui.layer;
        let table =layui.table;
        let $=layui.$;
        let transfer=layui.transfer;
        let attr_group_id;//用于修改分组信息的Id


        //添加非分类属性分组

        $("#addgroupby").on('click', function () {
            layer.open({
                type: 1,
                skin: 'demo-class',
                area: ['500px', '500px'],
                anim: 5,
                content: $('#div_add_group'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['关闭'],
                yes: function (index, layero) {

                    layer.close(index);
                }
            });
            return false;
        })

        //添加分组信息
        $("#btn_add_addgroup").on('click',function () {
            $.ajax({
                url: glodate.serverZuul + "attrGroup/insertGroupBy",
                method: "post",
                data: form.val('add_add_group'),
                success: function (res) {
                    console.log(res);
                    if (res.code == 200) {
                        layer.msg("添加成功！", {icon: 6});
                        setTimeout(' location.reload()', 2000);
                    } else {
                        layer.alert(res.msg, {icon: 5})
                    }
                    return false;
                }
            })
        })


        //先默认查询去全部的分组信息
        table.render({
            elem:'#catalogTab',
            url:glodate.serverZuul+'attrGroup/findNotGroupByCatelogId',
            id:'catalogReload',
            width:1200,
            page:true,

            cols:[[
                {
                    field:'attr_group_id',
                    title:'分组Id',
                    fixed:'left',
                    width:100
                },
                {
                    field:'attr_group_name',
                    title:'组名',
                    fixed:'left',
                    width:100
                },
                {
                    field:'descript',
                    title:'描述信息',
                    fixed:'left',
                    width:100
                },
                {
                    field:'sort',
                    title:'排序',
                    fixed:'left',
                    width:100
                },
                {
                    field:'icon',
                    title:'组图标',
                    fixed:'left',
                    width:100
                },
                {
                    field:'catelog_id',
                    title:'所属分类id',
                    fixed:'left',
                    width:100
                },
                {
                    title:'操作',
                    fixed:'left',
                    width:220,
                    toolbar:'#toolbartab'
                },
            ]]
        })

        //渲染树菜单节点
        $(function (){
            $.ajax({
                type:'get',
                url:glodate.serverZuul+'category/getTree',
                dataType:"json",
                success:function (res){
                    console.log(res.data);
                    tree.render({
                        elem:'#catalogTree',
                        data:res.data,
                        edit:['add'],
                        id:'treerenderId',
                        operate: function(obj){
                            var type = obj.type; //得到操作类型：add、edit、del
                            var data = obj.data; //得到当前节点的数据
                            var elem = obj.elem; //得到当前节点元素

                            //Ajax 操作
                            var id = data.id; //得到节点索引
                            if(type === 'add'){ //增加节点

                                //为当前分类添加一个属性
                                tree.reload('treerenderId', {}); //防止layui源码自动添加节点
                                console.log(data);
                                //打开添加分组页面
                                if(data.cat_level==3){
                                    $('#catalogIdByForm').val(id);
                                    //只能通过层级为3的分组打开
                                    attrVue.attrGroupCatalog(data.id);
                                    form.render('select');
                                    layer.open({
                                        type:1,
                                        area:['500px','400px'],
                                        content:$('#attrgroupForm'),
                                        title:'为分类<span style="color: red"> '+data.title+'</span> 添加分组'
                                    })
                                }

                            }
                        },
                        click:function (obj){
                            let data=obj.data; //得到当前点击的节点数据
                            //   console.log(obj.state); //得到当前节点的展开状态：open、close、normal
                            //  console.log(obj.elem); //得到当前节点元素
                            //当层级为3的时候，也就是我们的第三级分类
                            if(data.cat_level==3){
                                //点击数节点的时候每次都发一个请求来查看当前分类下的分组
                                table.reload('catalogReload',{
                                    url:glodate.serverZuul+'attrGroup/findGroupByCatelogId',
                                    where:{'catelogId':data.id}
                                })
                            }

                        }
                    })
                }
            })
        })
        //监听工具条
        table.on('tool(toolfilter)',function (obj){
            let data = obj.data; //获得当前行数据
            let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            let tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            let cat_id=data.catelog_id;
            if(layEvent=="exit"){
                //进行修改时先去判断他是否有所属分类
                attr_group_id=data.attr_group_id;
                if(data.catelog_id!=0){
                    //打开选择给所属分类添加分组页面和修改分组信息
                    Swal.fire({
                        icon:'info',
                        title:'请选择打开的页面',
                        text:'请仔细选择，这将影响到为你打开的窗口',
                        confirmButtonColor: '#14e0e0',
                        confirmButtonText: '修改分组的属性',
                        showCancelButton: true,
                        cancelButtonColor: '#1ad455',
                        cancelButtonText: '修改分组名'
                    }).then((x)=>{
                        //选择修改分组的属性的按钮
                        if(x.value){
                            //渲染穿梭框
                            $.ajax({
                                url:glodate.serverZuul+"attrGroup/findAllAttr",
                                method:'get',
                                data:{'cat_id':cat_id},
                                dataType:'json',
                                success:function (res){
                                    let catelog_id=data.catelog_id
                                    //渲染穿梭框
                                    //渲染
                                    $.ajax({
                                        url:glodate.serverZuul+"attrGroup/findAllGroupByCatelogIdandGroupId",
                                        data:{'catelogId':catelog_id,'attr_group_Id':attr_group_id},
                                        method:'get',
                                        dataType:'json',
                                        success:function (resultid){
                                            let attr_id_Array=[];
                                            for(let i=0;i<resultid.data.length;i++){
                                                attr_id_Array.push(resultid.data[i].attr_id)
                                            }
                                            transfer.render({
                                                elem: '#transferByGroup'  //绑定元素
                                                ,data: res.data
                                                ,value:attr_id_Array
                                                ,title:['未拥有','已拥有']
                                                ,id: 'transferByAttr' //定义索引
                                                ,showSearch:true
                                                ,parseData:function (parse){
                                                    return {
                                                        "value":parse.attr_id,
                                                        "title":parse.attr_name,
                                                        "disabled":false,
                                                        "checked":false,
                                                    }
                                                }
                                                ,onchange:function (data,index){
                                                    console.log(data);
                                                    console.log(index);
                                                    if(index==0){
                                                        //为分类新增属性
                                                        let value=[];
                                                        for(let i=0;i<data.length;i++){
                                                            value.push(data[i].value);
                                                        }
                                                        $.ajax({
                                                            url:glodate.serverZuul+"attrGroup/addGroupByCatalogIdandAttr",
                                                            method:'post',
                                                            data:{'AttrIdStr':value.join(","),'catelogId':catelog_id,'attr_group_id':attr_group_id},
                                                            dataType:'json',
                                                            success:function (res){
                                                                if(res.code==200){
                                                                    layer.msg('添加成功', {
                                                                        icon: 1,
                                                                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                                                    }, function(){
                                                                        location.reload()
                                                                        //do something
                                                                    });
                                                                }else{
                                                                    layer.msg("服务器再开小差，请稍后重试")
                                                                }

                                                                console.log(res);
                                                            }
                                                        })
                                                        //  console.log("添加:"+value)
                                                    }else{
                                                        //为分类移除属性

                                                        let value=[];
                                                        for(let i=0;i<data.length;i++){
                                                            value.push(data[i].value);
                                                        }
                                                        $.ajax({
                                                            url:glodate.serverZuul+"attrGroup/delGroupByCatalogIdandAttr",
                                                            method:'delete',
                                                            data:{'AttrIdStr':value.join(","),'catelogId':catelog_id,'attr_group_id':attr_group_id},
                                                            dataType:'json',
                                                            success:function (res){
                                                                if(res.code==200){
                                                                    layer.msg('移除成功', {
                                                                        icon: 1,
                                                                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                                                    }, function(){
                                                                        location.reload()
                                                                        //do something
                                                                    });
                                                                }else{
                                                                    layer.msg("服务器再开小差，请稍后重试")
                                                                }
                                                                console.log(res);
                                                            }
                                                        })
                                                        //  console.log("移除:"+value)

                                                    }
                                                }
                                            });

                                        }
                                    })



                                }
                            })

                            layer.open({
                                type:1,
                                area:['500px','450px'],
                                content:$('#transferByGroup'),
                                title:'修改分组的属性'
                            })

                        }else{
                            //选择修改分组名的按钮
                            //打开修改分类名称的窗口
                            layer.open({
                                type:1,
                                area:['400px','200px'],
                                content:$('#groupNameForm'),
                                title:'修改分组名'
                            })
                        }
                    })
                }else{

                    //如果为0说明他没有其他选项，只能进行修改分类名称
                    layer.open({
                        type:1,
                        area:['400px','200px'],
                        content:$('#groupNameForm'),
                        title:'修改分组名'
                    })
                }




            }else if(layEvent=="del"){
                //点击了删除按钮
                if(data.catelog_id==0||data.catelog_id==null){
                    //如果分类为0，说明这个分组没有分类来使用
                    let attr_group_id=data.attr_group_id;
                    //sweetalert2的页面弹窗方法
                    Swal.fire({
                        icon:'error',
                        title:'删除分组信息',
                        text:"删除后将无法恢复，请谨慎操作",
                        confirmButtonColor: '#3085d6',
                        confirmButtonText: '确定',
                        showCancelButton: true,
                        cancelButtonColor: '#d33',
                        cancelButtonText: "取消"
                    }).then((x)=>{
                        //如果为true的时候，也就是点击了确定按钮
                        if(x.value){
                            $.ajax({
                                url:glodate.serverZuul+"attrGroup/delGroupById/"+attr_group_id,
                                method:'delete',
                                dataType:'json',
                                success:function (res){
                                    if(res.code==200){
                                        Swal.fire({
                                            title:'删除成功',
                                            text:'即将刷新页面',
                                            icon:'success',

                                        })
                                    }else if(res.code==500){
                                        Swal.fire({
                                            title:'服务器在开小差',
                                            text:'请稍后再试',
                                            icon:'warning',
                                        })
                                    }
                                }
                            })
                        }

                    })
                }else{
                    //当前分组下还关联有商品分类
                   layer.alert("当前分组下还有关联的商品分类无法删除")
                }

            }


        })
        //查看没有分配到分组下的分类
        $('#notattrgroup').on('click',function (res){
            table.reload('catalogReload',{
                url:glodate.serverZuul+'attrGroup/findNotGroupByCatelogId',
            })
            return false;
        })
        //修改分组名称信息
        $('#groupNameBtn').on('click',function (){
            let name=$('#groupName').val();
            $.ajax({
                url:glodate.serverZuul+"attrGroup/updateGroupById",
                method:'put',
                data:{
                    'attr_group_id':attr_group_id,
                    'attr_group_name':name
                },
                dataType:'json',
                success:function (res){
                    if(res.code==200){
                        layer.msg("修改成功",function (){
                            location.reload();
                        })
                    }else{
                        Swal.fire({
                            title:'服务器出小差了',
                            text:'请稍后再试',
                            icon:'error',
                        })
                    }
                }
            })
            return false;
        })
        //为分类添加属性
        form.on('submit(addcententtable)',function (res){
            let attrgroupFormfilter=form.val('attrgroupFormfilter');
            console.log("------    "+JSON.stringify(attrgroupFormfilter));
            $.ajax({
                url:glodate.serverZuul+"attrGroup/addGroupByCatalogIdandAttr",
                method:'post',
                data:{'AttrIdStr':attrgroupFormfilter.attr_id,'catelogId':attrgroupFormfilter.catelog_id,'attr_group_id':attrgroupFormfilter.attr_group_id},
                dataType:'json',
                success:function (res){
                    if(res.code==200){
                        layer.msg('添加成功', {
                            icon: 1,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                          //  location.reload()
                            //do something
                        });
                    }else{
                        layer.msg("服务器再开小差，请稍后重试")
                    }

                    console.log(res);
                }
            })
            return false;
        })

    })
</script>
<script id="toolbartab" type="text/html">
    <input type="button" class="layui-btn layui-btn-normal layui-btn-sm" lay-event="exit" value="修改">
    <input type="button" class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del" value="删除">
</script>


</html>